//
//  YKStateMachine.m
//  YK_BaseTools
//
//  Created by edward on 2021/9/30.
//

#import "YKStateMachine.h"


@interface YKStateMachine()
@property (nonatomic,strong) NSDictionary *states;
@property (nonatomic,copy)   NSString *currentStateName;
@end

@implementation YKStateMachine


- (void)dealloc {
#ifdef DEBUG
    NSLog(@"⚠️状态机被释放了");
#endif
}
 
// MARK:根据传入的可选状态初始化状态机
+ (instancetype)stateMachineWithStates:(NSDictionary *)states {
    YKStateMachine *stateMachine = [[YKStateMachine alloc] init];
    stateMachine.states = states;
    stateMachine.currentStateName =@"";
    return stateMachine;
}

- (BOOL)canEnterState:(NSString *)stateName {
    return [self.states.allKeys containsObject:stateName];
}

- (BOOL)enterState:(NSString *)stateName container:(id<YKStateMachineContainerProtrocol>)container{
    id<YKStateMachineProtrocol>currentState;
    if (self.currentStateName.length != 0) {
        currentState = [self.states objectForKey:self.currentStateName];
    }
    
    if ([stateName isEqualToString:self.currentStateName]) {
        // 已经是当前状态
        return NO;
    }
    if ([self canEnterState:stateName]) {
        if ([currentState respondsToSelector:@selector(willExitWithNextState:)]) {
            [currentState willExitWithNextState:stateName];
        }

        id<YKStateMachineProtrocol>nextState = [self.states objectForKey:stateName];
        if ([nextState respondsToSelector:@selector(didEnterWithPreviousState:container:)]) {
            [nextState didEnterWithPreviousState:self.currentStateName container:container];
            self.currentStateName = stateName;
        }
        // 进入了下一个状态
        return YES;
    } else {
        // 不能进入该状态
        return NO;
    }
}

- (NSString *)currentStateName {
    return _currentStateName;
}

@end
